package com.villaday.idf.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import androidx.annotation.RequiresApi;
import androidx.palette.graphics.Palette;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.adapter.InviteDownloadAdapter;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.BaseNoWhiteActivity;
import com.villaday.idf.custom.CoverModeTransformer;
import com.villaday.idf.custom.FastBlur;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.custom.ShareNoCollectDialog;
import com.villaday.idf.model.VipsDownloadShare;
import com.villaday.idf.model.VipsInviteDetailDetailEntity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.GlideCircleTransform;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.villaday.idf.activity.InviteLiBaoActivity.getRoundedCornerBitmap;


/*
 * SVIP会员中心-邀请好友的海报页面
 * */
public class SVIPFreeActivity extends BaseNoWhiteActivity implements ViewPager.OnPageChangeListener, OkHttpUtil.OnDataListener, BaseDialog.OnItemClickListener {

    @BindView(R.id.vp)
    ViewPager vp;


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;

    @BindView(R.id.img)
    ImageView img;


    private Gson gson = new GsonBuilder().create();

    private List<ImageView> imgs = new ArrayList<>();
    private InviteDownloadAdapter vpMyPromotionAdapter;
    private LoadingDialog loadingDialog;
    private VipsDownloadShare.BodyEntity shareBody;
    private int position;
    private VipsInviteDetailDetailEntity vipsInviteDetailDetailEntity;
    private String imageFileName;


    @Override
    protected int getViewResId() {
        return R.layout.activity_svipfree;
    }

    @Override
    protected void init() {
        ToolBarUtil.initToolBar(toolbarText, "免费邀请", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        StatusBarUtil.setLightMode(this);

        vpMyPromotionAdapter = new InviteDownloadAdapter(this, imgs);
        vp.setAdapter(vpMyPromotionAdapter);

        vp.setOffscreenPageLimit(5);
        vp.addOnPageChangeListener(this);

        vp.setPageTransformer(true, new CoverModeTransformer(vp));

    }

    @Override
    protected void loadData() {
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getFragmentManager(), "loading");
        Map<String ,String> map=new HashMap<>();
        map.put("upgrade", getIntent().getStringExtra("upgrade"));
        map.put("IdfActivityId", getIntent().getStringExtra("IdfActivityId"));

        OkHttpUtil.getJSON(this, Constant.URL.vips_invite_free_detail,map, this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.position = position;

        //gaoSi(position);

        //moHuBG();
    }

    private void moHuBG() {
        imgs.get(position).setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(imgs.get(position).getDrawingCache());
        imgs.get(position).setDrawingCacheEnabled(false);
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                //记得判空
                if (palette == null) return;
                //palette取色不一定取得到某些特定的颜色，这里通过取多种颜色来避免取不到颜色的情况
                if (palette.getDarkVibrantColor(Color.TRANSPARENT) != Color.TRANSPARENT) {
                    createLinearGradientBitmap(palette.getDarkVibrantColor(Color.TRANSPARENT), palette.getVibrantColor(Color.TRANSPARENT));
                } else if (palette.getDarkMutedColor(Color.TRANSPARENT) != Color.TRANSPARENT) {
                    createLinearGradientBitmap(palette.getDarkMutedColor(Color.TRANSPARENT), palette.getMutedColor(Color.TRANSPARENT));
                } else {
                    createLinearGradientBitmap(palette.getLightMutedColor(Color.TRANSPARENT), palette.getLightVibrantColor(Color.TRANSPARENT));
                }

            }
        });
    }

//创建线性渐变背景色
        private void createLinearGradientBitmap(int darkColor,int color) {
            int bgColors[] = new int[2];
            bgColors[0] = darkColor;
            bgColors[1] = color;

            Bitmap bgBitmap = null;
            if(bgBitmap==null){
                bgBitmap= Bitmap.createBitmap(img.getWidth(),img.getHeight(), Bitmap.Config.ARGB_4444);
            }
            Canvas mCanvas = null;
            if(mCanvas==null){
                mCanvas=new Canvas();
            }
            Paint mPaint = null;
            if(mPaint==null){
                mPaint=new Paint();
            }
            mCanvas.setBitmap(bgBitmap);
            mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            LinearGradient gradient=new LinearGradient(0, 0, 0, bgBitmap.getHeight(),bgColors[0],bgColors[1], Shader.TileMode.CLAMP);
            mPaint.setShader(gradient);
            RectF rectF=new RectF(0,0,bgBitmap.getWidth(),bgBitmap.getHeight());
            // mCanvas.drawRoundRect(rectF,16,16,mPaint); 这个用来绘制圆角的哈
            mCanvas.drawRect(rectF,mPaint);
            img.setImageBitmap(bgBitmap);
        }

    //高斯模糊
    private void gaoSi(int position) {
        imgs.get(position).setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(imgs.get(position).getDrawingCache());
        imgs.get(position).setDrawingCacheEnabled(false);

        img.setImageBitmap(FastBlur.fastBlur(bitmap, 10f));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onResponse(String url, String json) {
        dismissLoading();
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.vips_invite_free_detail.equals(url)) {
                LogeUtil.e("vips_invite_free_detail", json);
                vipsInviteDetailDetailEntity = gson.fromJson(json, VipsInviteDetailDetailEntity.class);
                if ("200".equals(vipsInviteDetailDetailEntity.getCode())) {
                    tvTitle.setText(vipsInviteDetailDetailEntity.getBody().getDescription());

                    for (int i = 0; i < vipsInviteDetailDetailEntity.getBody().getPosters().size(); i++) {
                        initImgs(vipsInviteDetailDetailEntity.getBody().getPosters().get(i));

                    }


                    vpMyPromotionAdapter.notifyDataSetChanged();

                   /* new Thread(new Runnable() {
                        @Override
                        public void run() {
                            URL imageurl = null;

                            try {
                                imageurl = new URL(vipsInviteDetailDetailEntity.getBody().getPosters().get(0));
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                            try {
                                HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                                conn.setDoInput(true);
                                conn.connect();
                                InputStream is = conn.getInputStream();
                                final Bitmap bitmap;
                                bitmap = BitmapFactory.decodeStream(is);
                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        //更新UI
                                        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
                                            @Override
                                            public void onGenerated(Palette palette) {
                                                //记得判空
                                                if (palette == null) return;
                                                //palette取色不一定取得到某些特定的颜色，这里通过取多种颜色来避免取不到颜色的情况
                                                if (palette.getDarkVibrantColor(Color.TRANSPARENT) != Color.TRANSPARENT) {
                                                    createLinearGradientBitmap(palette.getDarkVibrantColor(Color.TRANSPARENT), palette.getVibrantColor(Color.TRANSPARENT));
                                                } else if (palette.getDarkMutedColor(Color.TRANSPARENT) != Color.TRANSPARENT) {
                                                    createLinearGradientBitmap(palette.getDarkMutedColor(Color.TRANSPARENT), palette.getMutedColor(Color.TRANSPARENT));
                                                } else {
                                                    createLinearGradientBitmap(palette.getLightMutedColor(Color.TRANSPARENT), palette.getLightVibrantColor(Color.TRANSPARENT));
                                                }
                                            }
                                        });

                                    }
                                });


                                //这是一个一步请求，不能直接返回获取，要不然永远为null
                                //在这里得到BitMap之后记得使用Hanlder或者EventBus传回主线程，不过现在加载图片都是用框架了，很少有转化为Bitmap的需求
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();*/


                    // gaoSi(position);
                }


            } else if (Constant.URL.vips_invite_gifts_share.equals(url)) {
                LogeUtil.e("vips_invite_gifts_share", json);
                VipsDownloadShare vipsDownloadShare = gson.fromJson(json, VipsDownloadShare.class);
                if ("200".equals(vipsDownloadShare.getCode())) {
                    shareBody = vipsDownloadShare.getBody();



                    /*if ("mini".equals(shareBody.getType())) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                saveImageToSdCard(this, shareBody.getImageUrl());

                                shareXCX();
                            }
                        }).start();
                    } else {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                saveImageToSdCard(this, shareBody.getImageUrl());
                                ShareNoCollectDialog shareDialog = ShareNoCollectDialog.newInstance();
                                shareDialog.show(getActivity().getFragmentManager());
                                shareDialog.setOnItemClickListener(SvipFreeFragment.this);
                                //shareXCX();
                            }
                        }).start();
                    }*/

                } else {
                    ToastUtil.initToast(this, vipsDownloadShare.getMsg());
                }


            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initImgs(String url) {
      /*  ImageView image = new ImageView(this);
        image.getLayoutParams().height=LinearLayout.LayoutParams.MATCH_PARENT;
                image.getLayoutParams().width=LinearLayout.LayoutParams.MATCH_PARENT;


        image.setScaleType(ImageView.ScaleType.FIT_CENTER);
        image.requestLayout();*/

        final ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); //设置图片宽高

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.ic_replace)
                .error(R.drawable.ic_replace)
                .priority(Priority.HIGH)
                .centerCrop()
                .transform(new GlideCircleTransform(this, PhoneUtil.dp2px(this, 5)));

        Glide.with(this)
                .asBitmap()
                .load(url)
                .apply(options)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        int width = resource.getWidth();
                        int height = resource.getHeight();
                        imageView.getLayoutParams().width = PhoneUtil.dp2px(SVIPFreeActivity.this, 280);

                        imageView.getLayoutParams().height = PhoneUtil.dp2px(SVIPFreeActivity.this, 410);
                        imageView.requestLayout();
                        Bitmap roundedCornerBitmap = getRoundedCornerBitmap(resource, 15);
                        imageView.setImageBitmap(roundedCornerBitmap);
                        imageView.setPadding(PhoneUtil.dp2px(SVIPFreeActivity.this, 5), 0, PhoneUtil.dp2px(SVIPFreeActivity.this, 5), 0);

                    }


                });

        imageView.setElevation(10f);
        imgs.add(imageView);

    }

    @Override
    public void onFailure(String url, String error) {

    }


    @OnClick({R.id.tv_shareLink, R.id.tv_sharePhoto, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_shareLink: {
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;

                mClipData = ClipData.newPlainText("test", SharedPreferencesUtil.getUserInfo(this).getBody().getMember().getInviteCode());
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(this, "邀请码已复制，去粘贴");

               /* loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                OkHttpUtil.getJSON(this, Constant.URL.vips_invite_gifts_share, this);*/

            }


            break;
            case R.id.tv_sharePhoto:
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (vipsInviteDetailDetailEntity == null) {
                            return;
                        }
                        saveImageToSdCard(SVIPFreeActivity.this, vipsInviteDetailDetailEntity.getBody().getPosters().get(position));
                        ShareNoCollectDialog shareDialog = ShareNoCollectDialog.newInstance();
                        shareDialog.show(getFragmentManager());
                        shareDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                            @Override
                            public void onItemClick(View v) {
                                switch (v.getId()) {

                                    case R.id.tv_Swx: {

                                        shareXPhotoVipsDownloadDetailEntity(0);

                                        //share(0);
                                    }
                                    break;
                                    case R.id.tv_Spyq: {

                                        shareXPhotoVipsDownloadDetailEntity(1);


                                    }
                                    break;
                                    case R.id.tv_Ssave: {//收藏

                                        shareXPhotoVipsDownloadDetailEntity(2);


                                    }
                                    break;
                                }
                            }
                        });
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoading();
                            }
                        });

                    }
                }).start();

                break;
            case R.id.tv_save: {
                if (vipsInviteDetailDetailEntity == null) {
                    return;
                }

                List<String> picList = new ArrayList<>();
                picList.add(vipsInviteDetailDetailEntity.getBody().getPosters().get(position));
                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                loadingDialog.show(getFragmentManager(), "0");
                saveImageForRecursive(picList, picList.size(), loadingDialog);
            }
            break;
        }
    }

    public void saveImageForRecursive(final List<String> img, final int imgSize, final LoadingSaveDialog loadingSaveDialog) {//递归保存
        if (loadingSaveDialog != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingSaveDialog.setLoadingTips("已保存" + (imgSize - img.size() + 1) + "/" + imgSize + "张");
                }
            });

        }
        if (img.size() != 0) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveImageToSdCard(SVIPFreeActivity.this, img.get(0), true);

                    img.remove(0);
                    saveImageForRecursive(img, imgSize, loadingSaveDialog);
                }
            }
            ).start();
        } else {

            if (loadingSaveDialog != null) {

                loadingSaveDialog.dismiss();
            }
            Looper.prepare();
            String fileName;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
                fileName = "/DCIM/Camera/";
            } else {  // Meizu 、Oppo
                fileName = "/DCIM/Camera/";
            }
            ToastUtil.initToast(this, "图文保存至" + fileName);

            ToastUtil.initToast(this, "图文保存成功！快去发朋友圈推广吧~");
            Looper.loop();
        }

    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {

            case R.id.tv_Swx: {

                if ("mini".equals(shareBody.getType())) {
                    shareXCX();
                } else if ("music".equals(shareBody.getType())) {
                    shareXMusic(0);

                } else if ("video".equals(shareBody.getType())) {
                    shareXVideo(0);

                } else if ("link".equals(shareBody.getType())) {
                    share(0);


                } else if ("text".equals(shareBody.getType())) {
                    shareXText(0);


                } else if ("image".equals(shareBody.getType())) {
                    shareXPhoto(0);


                }
                //share(0);
            }
            break;
            case R.id.tv_Spyq: {

                if ("mini".equals(shareBody.getType())) {
                    share(1);
                } else if ("music".equals(shareBody.getType())) {
                    shareXMusic(1);

                } else if ("video".equals(shareBody.getType())) {
                    shareXVideo(1);

                } else if ("link".equals(shareBody.getType())) {
                    share(1);


                } else if ("text".equals(shareBody.getType())) {
                    shareXText(1);


                } else if ("image".equals(shareBody.getType())) {
                    shareXPhoto(1);

                }


            }
            break;
            case R.id.tv_Ssave: {//收藏
                if ("mini".equals(shareBody.getType())) {
                    share(2);

                } else if ("music".equals(shareBody.getType())) {
                    shareXMusic(2);

                } else if ("video".equals(shareBody.getType())) {
                    shareXVideo(2);

                } else if ("link".equals(shareBody.getType())) {
                    share(2);


                } else if ("text".equals(shareBody.getType())) {
                    shareXText(2);


                } else if ("image".equals(shareBody.getType())) {
                    shareXPhoto(2);

                }

            }
            break;
        }
    }

    private void shareXText(int i) {//0 聊天1 朋友圈 其他收藏

        WXTextObject miniProgramObj = new WXTextObject(shareBody.getTitle());
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.description = shareBody.getTitle();
        //Bitmap bitmap = BitMapUtil.getBitmap(fileName);


        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "text";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXPhotoVipsDownloadDetailEntity(int i) {//0 聊天1 朋友圈 其他收藏

        String imageFileName = this.imageFileName;
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;

        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        WXImageObject miniProgramObj = new WXImageObject(bitmap);
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
     /*   msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();*/
        //Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 30 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXPhoto(int i) {//0 聊天1 朋友圈 其他收藏

        String imageFileName = this.imageFileName;
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;

        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        WXImageObject miniProgramObj = new WXImageObject(bitmap);
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        //Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 30 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXVideo(int i) {//0 聊天1 朋友圈 其他收藏

        String imageFileName = this.imageFileName;
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;


        WXVideoObject miniProgramObj = new WXVideoObject();
        miniProgramObj.videoUrl = shareBody.getLink(); // 音乐
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 30 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "video";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXMusic(int i) {//0 聊天1 朋友圈 其他收藏

        String imageFileName = this.imageFileName;
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;


        WXMusicObject miniProgramObj = new WXMusicObject();
        miniProgramObj.musicUrl = shareBody.getLink(); // 音乐
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 30 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "music";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXCX() {

        String imageFileName = this.imageFileName;
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;


        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = shareBody.getLink(); // 兼容低版本的网页链接
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        miniProgramObj.userName = shareBody.getMiniAppId();     // 小程序原始id
        miniProgramObj.path = shareBody.getPath();            //小程序页面路径
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 100 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支持会话
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void share(int i) {
        String imageFileName = this.imageFileName;
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;
        String sharefileName = externalCacheDir.getPath() + "/12306" + imageFileName;


        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = shareBody.getLink();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = shareBody.getTitle();
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);
        /*Bitmap bitmap1 = BitMapUtil.compressBitmap(bitmap, 31*1024);
        BitMapUtil.saveBitmap2File(bitmap1,sharefileName);
        Bitmap bitmap2 = BitMapUtil.getBitmap(sharefileName);*/
        //Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.share);
        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 31 * 1024);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);
        api.sendReq(req);

    }

    //根据网络图片url路径保存到本地
    public File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {

            file = createStableImageFile(context);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {

            return file;
        } else {
            return null;
        }
    }

    //创建相册
    public File createXiangCeImageFile(Context context) throws IOException {
        imageFileName = "vipshare" + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public File createStableImageFile(Context context) throws IOException {

        imageFileName = "vipshare" + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    //根据网络图片url路径保存到本地
    public final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }


}
